//
// socket.h
// libprotea
// Tools Library for the Protea Project / Network Socket functionality
// Copyright (C) 2003, 2004, 2005 eXegeSys, Inc.
// Copyright (C) 2008 Bruce A. James
//
// This program is part of the Protea Project.
//
// The Protea Project is free software; you can redistribute it and/or modify it 
// under the terms of the GNU General Public License as published by the 
// Free Software Foundation, either version 3 of the License, or (at your 
// option) any later version.
//
// The Protea Project is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
// 
// You should have received a copy of the GNU General Public License along 
// with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Please send correspondence to:
// 
// theproteaproject@gmail.com
//

#ifndef __PROTEA_SOCKET_H__
#define __PROTEA_SOCKET_H__

#include "transport.h"

class __EXPORT XCSocketTransport : public XCTransport {
public:
	XCSocketTransport( XCAppInterface* app_owner, XCMsgPort* port_owner = NULL );
	XCSocketTransport( XCAppInterface* app_owner, SOCKET newsocket, XCMsgPort* port_owner = NULL );
	~XCSocketTransport();

	int		Send( const void* data, int size = -1);
	int		Recv( void* data, int size );
	int		Close();

	void	CancelIO();

	PORT_HANDLE GetInHandle();
	PORT_HANDLE GetOutHandle();

	// Transport specific calls

	/// Create a new socket
	void	Create( int af, int type, int protocol );

	/// Set the socket blocking mode
	void	SetBlockingMode( bool mode = true );

	/// Set the socket broadcast flag
	int		SetBroadcast( bool broadcast );

	/// Turn Nagle's algorithm on/off
	int		SetNagles( bool delay );

	/// Query Nagle's algorithm on/off
	bool	GetNagles();

	/// Create a socket connection
	void	Connect( const char* host, int port );

	/// Accept a socket connection
	XCSocketTransport* Accept( sockaddr* addr = NULL, int* len = NULL );

	/// Put a socket into listening mode
	bool	Listen( int backlog = 5 );

	/// Returns the port a socket is currently connected to
	int		GetPort();

	/// Causes the socket to be bound to a particular port
	void	Bind( int port );

protected:
	/// Socket handle
	SOCKET		mSocket;
};


// Auxiliary functions
__EXPORT int			XCSelectSocket( PORT_HANDLE n, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout);
__EXPORT void			XCSetupAddr( char* host, int port, sockaddr_in& addr );
__EXPORT int			XCGetHostName( char *name, int len );


#endif
